package com.ruoyi.common.utils.http;

import com.ruoyi.common.utils.ExceptionUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpsClientUtil {

    protected static final Logger logger = LoggerFactory.getLogger(HttpsClientUtil.class);


    private static CloseableHttpClient httpClient;

    static {
        try {
            SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
            RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
        } catch (Exception e) {
            logger.error("static异常！！！报错信息："+ ExceptionUtil.getExceptionMessage(e));
        }
    }

    public static String doPost(String url, String jsonString) {
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpPost.addHeader("User-Agent", "PostmanRuntime/7.26.8");
            httpPost.setHeader("Cookie","_ga=GA1.2.560051660.1603704790; AWSALB=w6hcBCKSOibXA9y407+GUD8VNinXhWNoylKbNJs3QvgMW3SvHoWkMFcIoRMdMM9jCxtQPvIlmJK+Ho/nfgP3fpByMKgHupbC4yhJnuR+uMCGoJoKQuOJ0+4fsaUd; AWSALBCORS=w6hcBCKSOibXA9y407+GUD8VNinXhWNoylKbNJs3QvgMW3SvHoWkMFcIoRMdMM9jCxtQPvIlmJK+Ho/nfgP3fpByMKgHupbC4yhJnuR+uMCGoJoKQuOJ0+4fsaUd; _gid=GA1.2.1073884922.1649220789");
            StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :"
                        + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            logger.error("POST请求异常！！！报错信息："+ ExceptionUtil.getExceptionMessage(e));
        }
        return null;
    }
    public static String sendPost(String url,String Params)throws IOException {
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        String response="";
        try {
            URL httpUrl = null; //HTTP URL类 用这个类来创建连接
            //创建URL
            httpUrl = new URL(url);
            //建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);//设置不要缓存
            conn.setInstanceFollowRedirects(true);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //POST请求
            out = new OutputStreamWriter(
                    conn.getOutputStream());
            out.write(Params);
            out.flush();
            //读取响应
            reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                response+=lines;
            }
            reader.close();
            // 断开连接
            conn.disconnect();

//            System.out.println(response);
        } catch (Exception e) {
            logger.error("POST请求异常！！！报错信息："+ ExceptionUtil.getExceptionMessage(e));
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(reader!=null){
                    reader.close();
                }
            }
            catch(IOException ex){
                logger.error("POST请求异常！！！报错信息："+ ExceptionUtil.getExceptionMessage(ex));
            }
        }

        return response;
    }
}
